<template>
  <div class="wrap">
    <ul class="tabs"
    >
      <li
        class="tab"
        v-for="tab in tabs"
        :key="tab.key"
        :class="{ active: currentTab === tab.component }"
        @click="switchTab(tab.component)"
      >
        {{tab.name}}
        <span v-if="tab.num > 0">({{tab.num > 100 ? '99+' : tab.num}})</span>
      </li>
    </ul>
    <div class="tabs-content">
      <keep-alive>
        <component :is="currentComponent" v-bind="compProps"></component>
      </keep-alive>
    </div>
  </div>
</template>

<script>
import SearchResultAll from './SearchResultAll.vue'
import SearchResultBangumi from './SearchResultBangumi.vue'
import SearchResultUser from './SearchResultUser.vue'
import SearchResultMovies from './SearchResultMovies.vue'
export default {
  name: 'SearchResult',
  provide () {
    return {
      setSearchTypeNum: this.setTabNum,
      switchSearchType: this.switchTab
    }
  },
  components: {
    SearchResultAll,
    SearchResultBangumi,
    SearchResultUser,
    SearchResultMovies
  },
  props: {
    keyword: {
      type: String
    }
  },
  data () {
    return {
      resultData: {},
      currentTab: 'all',
      tabs: [
        { id: 1, name: '综合', component: 'all', num: 0 },
        { id: 2, name: '番剧', component: 'bangumi', num: 0 },
        { id: 3, name: 'UP主', component: 'user', num: 0 },
        { id: 4, name: '影视', component: 'movies', num: 0 }
      ]
    }
  },
  computed: {
    currentComponent () {
      const comp = this.currentTab.charAt(0).toUpperCase() + this.currentTab.slice(1)
      return 'SearchResult' + comp
    },
    compProps () {
      return {
        keyword: this.keyword
      }
    }
  },
  watch: {
    keyword (newVal) {
      if (newVal) {
        this.currentTab = 'all'
      }
    }
  },
  methods: {
    switchTab (tab) {
      this.currentTab = tab
    },
    setTabNum (result) {
      const topTlist = result.top_tlist
      if (topTlist) {
        this.tabs.forEach(tab => {
          const comp = tab.component
          if (comp === 'bangumi') {
            tab.num = topTlist.media_bangumi
          } else if (comp === 'user') {
            tab.num = topTlist.bili_user
          } else if (comp === 'movies') {
            tab.num = topTlist.media_ft
          }
        })
      }
      return this.tabs
    }
  }

}
</script>

<style lang="scss" scoped>
  .wrap {
    min-height: calc(100vh - 54px);
    background-color: $color-grey;
  };
  .tabs {
    position: sticky;
    top: rem(49px);
    z-index: 2;
    display: flex;
    height: rem(44px);
    padding: 0 rem(20px);
    justify-content: space-between;
    background-color: $color-white;
    .tab{
      display: inline-block;
      height: rem(30px);
      line-height: rem(30px);
      font-size: rem(14px);
      margin-top: rem(7px);
      color: $color-text-regular;
      &.active{
        color: $theme-color;
        border-bottom: rem(2px) solid $theme-color;
      }
    }
  }
</style>
